<?php
/*
This sends a request to Google Refine to reconcile a field with Eol.org 
*/
error_reporting(E_ALL);
ini_set('display_errors', '1');


require_once( 'core.php' );
require_once( 'current_user_api.php' );

auth_ensure_user_authenticated( );
//helper_begin_long_process( );

$t_plugin_path = config_get( 'plugin_path' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'HTTPclient.php' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'ReconciliationServices.php' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'TableMetadata.php' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'JSONstore.php' );


$refineURI = plugin_config_get( 'refineLocalURI' );
if(!$refineURI){
	$refineURI = plugin_config_get( 'refineBaseURI' );
}



# extracts the user information for the currently logged in user
# and prefixes it with u_
$f_user_id = gpc_get_int( 'id', auth_get_current_user_id() );
$row = user_get_row( $f_user_id );

extract( $row, EXTR_PREFIX_ALL, 'u' );
$u_email = user_get_email( $u_id );
$u_realname = user_get_realname( $u_id );
$t_project_id = helper_get_current_project();




//check pending processes
	
	
	$RecServices = new ReconciliationServices;
	
	$RecServices->refineURI = $refineURI;
	
	$RecServices->reconKey = $_POST["reconKey"];
	$RecServices->GRprojectID = $_POST["grProject"];
	$RecServices->baseColumnName = $_POST["baseColumnName"];
	$RecServices->FinishColumnInsertIndex = ($_POST["baseColumnIndex"] + $_POST["finishIndex"]) ;
	
	
	if($_POST["test"] == "test"){
		
		$nextFinish = 1;
		$progress = 0;
		if(isset($_POST["progress"])){
			$progress = $_POST["progress"] + 5;
		}
		if(isset($_POST["finishIndex"])){
			$nextFinish = $_POST["finishIndex"] + 1;
			if($nextFinish>2){
				$nextFinish = 0;
			}
		}
		
		$message = array("testParams" => $_POST);
		
		if($progress < 100){
			$message["refineOK"] = "pending";
			$message["pending"][0] = array("id" => 12345678,
						       "description" => "Create column EOL JSON Data for at index 11 by fetching URLs based on column Taxon",
						       "status" => "running",
						       "progress" => $progress,
						       );
			$message["progress"] = $progress;
			$message["nextFinishIndex"] = 1;
		}
		else{
			$message["refineOK"] = true;
			$message["pending"] = false;
			$message["progress"] = 100;
			$message["nextFinishIndex"] = $nextFinish;
		}
	}
	else{
		//this is NOT a test!
		$message = $RecServices->ReconFinish($_POST["finishIndex"]);
	
		if(is_array($message)){
			//post the message starting the reconcilation Google Refine server
			$HTTPclient = new HTTPclient;
			
			$HTTPclient->refineBaseURI = $refineURI;
			$HTTPclient->postActionURI = $RecServices->finishCommandURL;
			$HTTPclient->authorized = $authorized;
			$HTTPclient->message = $message; //json data as a string
			$HTTPclient->postData(); //send the post!
			
			
			if($HTTPclient->success != false){
				$message["refineOK"] = true;
				$message["postURI"]= $HTTPclient->postURI;
				$responseMessage = json_decode($HTTPclient->responseData, true);
				$message["refineRespose"] = $responseMessage;
				$message["pending"] = false;
				$message["progress"] = 100;
				$message["nextFinishIndex"] = $RecServices->nextFinishIndex;
				
				$ActRecService = $RecServices->getSettings($_POST["reconKey"]);
				
				$tableMetaObj = new TableMetadata;
				$tableMetaObj->refineURI = $refineURI;
				$tableMetaObj->currentUser = $f_user_id;
				$tableMetaObj->GRprojectID = $_POST["grProject"];
				$tableMetaObj->get_metadata();
				$tableMetadata = $tableMetaObj->currentMetadata;
				
				if($_POST["finishIndex"] == 1){
					//added a field! now add a note to the field, but only for the first column parsed for results
					
					$note = "This column was related to ".$ActRecService["title"]." (".$ActRecService["about"].") on ".date("Y-m-d");
					
					$newNote = array("text" => $note,
							 "noteCreator" => $u_username,
							 "skipNote" => false
							 );
					$tableMetadata["reconciled"][$_POST["baseColumnName"]]["baseNote"] = $newNote;
				}
				
				//now add a note for the current column added from the Reconciliation results
				$derivedCol = array();
				$derivedCol["columnName"] = $message["newColumnName"];
				$note = "This column derived from the column ".$RecServices->baseColumnName." using the reconcilation service: ";
				$note .= $ActRecService["title"]." (".$ActRecService["about"].") on ".date("Y-m-d").". ";
				$note .= "Values in this column came from further processing of raw reconciliation service results. ";
				
				$newNote = array("text" => $note,
						"noteCreator" => $u_username,
						"skipNote" => false
						);
				$derivedCol["note"] = $newNote;
				$derivedCol["serviceURL"] = $ActRecService["baseURL"];
				
				$tableMetadata["reconciled"][$_POST["baseColumnName"]]["derivedCols"][] = $derivedCol;
					
				//now save the new notes addedto the fields
				$json = json_encode($tableMetadata, 1);
				$JSONstore = new JSONstore;
				$JSONstore->setDirectory("metadata");
				$JSONstore->save_json($RecServices->GRprojectID, $json); //save the metadata to the table metadata, can use to auto populate column doc
				
				$message["note"] = $tableMetadata["reconciled"][$_POST["baseColumnName"]]; //for debugging
				
			}
			else{
				$message["refineOK"] = false;
				$message["postURI"]= $HTTPclient->postURI;
				$message["error"] = $HTTPclient->errorMessage;
				$message["pending"] = false;
				$message["progress"] = 0;
				$message["nextFinishIndex"] = 0;
			}
		}
		else{
			if(is_array($RecServices->pendingProcesses)){
				$message["refineOK"] = "pending";
				$message["error"] = "Waiting for pending processes (".count($RecServices->pendingProcesses).")";
				$message["pending"] = $RecServices->pendingProcesses;
				$message["progress"] = $RecServices->pendingProgress;
				$message["nextFinishIndex"] = 1;
				
				if($_POST["progress"] == 0){
					if(!is_array($RecServices->getReconProcess())){
						$RecServices->cacheReconProcess($_POST);
					}
				}
				
			}
			else{
				$message["nextFinishIndex"] = 0;
			}
		}
	}//end case of not a test

$output = json_encode($message, 1);

//now output for AJAX call from the Refine Login Screen
if(!isset($_GET["callback"])){
	header('Content-Type: application/json; charset=utf8');
	echo $output;
}
else{
	header('Content-Type: application/json; charset=utf8');
	$callback = $_GET["callback"];
	echo $callback."(".$output.");";
}


?>
